package com.copycatTomcat.server;

import com.copycatTomcat.dispatcher.ProcessDispatcher;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;



public class Server {
	private static boolean shutDown = false;


    public static void main(String[] args) throws IOException {
        Server server = new Server();
        server.startServer();
    }

    public void startServer() throws IOException {
        ServerSocket serverSocket = null;
        try {

            serverSocket = new ServerSocket(8088);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        while(!shutDown) {
            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;
            try {

                socket = serverSocket.accept();

                input = socket.getInputStream();

                output = socket.getOutputStream();

                ProcessDispatcher processDispatcher = new ProcessDispatcher(input, output);
                processDispatcher.service();

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(socket != null) {
                    socket.close();
                }

                if(input != null) {
                    input.close();
                }

                if(output != null) {
                    output.close();
                }
            }
        }
    }
}
